import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

/**
 * 单选与复选框
 * Switch和复选框Checkbox，虽然它们都是继承自StatefulWidget
 */
class CheckBoxWidget extends StatefulWidget {
  CheckBoxWidget({
    Key ?key,
    @required this.text,
  }) : super(key: key);
  final String ? text;

  @override
  State<StatefulWidget> createState() {
    return _CheckSwitchState(text??"");
  }
}

class _CheckSwitchState extends State<CheckBoxWidget> {
  String ?text;
  bool _switchSelected = true; //维护单选开关状态
  bool _checkboxSelected = true; //维护复选框状态
  _CheckSwitchState(String ?str) {
    this.text = str;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        backgroundColor: Colors.grey[300], //背景色

        appBar: AppBar(
          title: Text(text??""),
        ),
        body: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            new Row(
              children: [
                Switch(
                  value: _switchSelected, //当前状态
                  onChanged: (value) {
                    //重新构建页面
                    setState(() {
                      _switchSelected = value;
                    });
                  },
                ),
                Text(
                  _switchSelected ? "开" : "关",
                  style: TextStyle(
                    color: Colors.blue,
                    fontSize: 18.0,
                    height: 1.2,
                    fontFamily: "Courier",
                  ),
                )
              ],
            ),
            Checkbox(
              value: _checkboxSelected,
              activeColor: Colors.red, //选中时的颜色
              onChanged: (value) {
                setState(() {
                  _checkboxSelected = value!;
                });
              },
            )
          ],
        ));
  }
}
